import React from 'react'
import {
  Form,
  Input,
  Button,
  Toast
} from 'antd-mobile'
import { loginApi} from '@/api/login'
import { useDispatch } from 'react-redux'
import {useHistory } from  'react-router-dom'

export default function MyLoginForm() {
  const dispatch = useDispatch()
  // 获取表单实例
  const [form] = Form.useForm()
  const his = useHistory()
  const onSubmit = () => {
    const values = form.getFieldsValue()
    console.log('value', values);
    loginApi(values).then(res=>{
      console.log(res);
      // 如果登录成功,给出提示登录成功 === 存token到本地,存用户信息到redux仓库 === 跳转页面
      if(res.data.code == 200){
        Toast.show({
          content:'登录成功',
          afterClose:()=>{
            // toast关闭后的回调 == 跳转页面
            his.push('/home')
          }
        })
        localStorage.setItem('token',res.data.data.token)
        dispatch({
          type:'setUser',
          payload:res.data.data.userid
        })
      }
    })
  }
  return (
    <>
      <Form
        // 赋值Form表单实例
        form={form}
        layout='horizontal'
        footer={
          <Button style={{
            borderRadius:'30px'
          }} block type='submit' color='danger' size='large'
            onClick={onSubmit}>
            提交
          </Button>
        }
      >
        <Form.Item
          name='loginname'
          label='用户名'
          rules={[{ required: true, message: '用户名不能为空' }]}
        >
          <Input placeholder='请输入用户名' />
        </Form.Item>
        <Form.Item name='password' label='密码'
          rules={[{ required: true, message: '密码不能为空' }]}>
          <Input placeholder='请输入密码' />
        </Form.Item>
      </Form>
    </>
  )
}
